package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import jdk.nashorn.internal.ir.IfNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private IArticleClient iArticleClient;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    //@Async
    @GlobalTransactional
    public void autoScanWmNews(Integer id) throws Exception {
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl--文章不存在");
        }

        if (WmNews.Status.SUBMIT.getCode() == wmNews.getStatus()) {
            //从文章中提取内容和图片
            Map textAndImages = handleTextAndImages(wmNews);
            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) textAndImages.get("text"), wmNews);
            if(!isSensitive) return;
            //审核文本内容
            boolean isTextScan = handleTextScan(wmNews, textAndImages.get("text").toString());
            if (!isTextScan) return;
            //审核图片内容
            boolean isImageScan = handleImageScan(wmNews, (List<String>) textAndImages.get("images"));
            if (!isImageScan) return;
            //审核成功,保存app端文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl--app端数据丢失");
            }

            //回填articleId
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,(short)9,"审核成功");
        }
    }


    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    //自管理的敏感词过滤
    private boolean handleSensitiveScan(String text, WmNews wmNews) {
        boolean flag = true;
        //获取所有的敏感词库
        List<WmSensitive> wmSensitives = wmSensitiveMapper
                .selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitives = wmSensitives.stream()
                .map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitives);
        //查看文章中是否包含敏感词
        Map<String, Integer> matchWords = SensitiveWordUtil.matchWords(text);
        if (matchWords.size() > 0){
            updateWmNews(wmNews,(short)2,"当前文章中存在违规内容" + matchWords);
            flag = false;
        }
        return flag;
    }


    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmChannelMapper wmChannelMapper;

    /**
     * 远程调用保存文章的方法
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) throws InvocationTargetException, IllegalAccessException {
        ArticleDtoBuilder articleDtoBuilder = new ArticleDtoBuilder(wmNews, wmChannelMapper, wmUserMapper);
        //使用构造器设计模式 方便以后维护
        //构造器设计模式：他最适合用于构建复杂得对象
        // 1、VO 对象
        // 2、一个系统调用另一个系统得时候， 另一个系统，需要一个对象来操作,而且这个对象本身还挺复杂
        ArticleDto articleDto = articleDtoBuilder
                .buildBeanCopy()
                .buildAuthor()
                .buildBasic()
                .buildChannel()
                .buildAuthor()
                .buildBasic()
                .builder();
        return iArticleClient.saveArticle(articleDto);

    }

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核文本内容
     *
     * @param wmNews
     * @param images
     * @return
     */
    private boolean handleImageScan(WmNews wmNews, List<String> images) throws Exception {
        boolean flag = true;
        if (images != null || images.size() != 0) {
            List<byte[]> imageBytes = new ArrayList<>();
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                //图片识别文字审核
                //从byte数组转换为butteredImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(in);
                //识别图片的文字的
                String result = tess4jClient.doOCR(imageFile);
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if (!isSensitive) return isSensitive;
                imageBytes.add(bytes);
            }
            Map map = greenImageScan.imageScan(imageBytes);
            if (map != null) isFlag(wmNews, flag, map);
        }
        return flag;
    }


    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 审核文本内容
     *
     * @param wmNews
     * @param text
     * @return
     */
    private boolean handleTextScan(WmNews wmNews, String text) throws Exception {
        boolean flag = true;
        Map map = greenTextScan.greeTextScan(text);
        if (map != null) flag = isFlag(wmNews, flag, map);

        return flag;
    }

    /**
     * 解析审核结果
     *
     * @param wmNews
     * @param flag
     * @param map
     * @return
     */
    private boolean isFlag(WmNews wmNews, boolean flag, Map map) {
        if ("block".equals(map.get("suggestion"))) {
            flag = false;
            updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
        }
        if ("review".equals(map.get("suggestion"))) {
            flag = false;
            updateWmNews(wmNews, (short) 3, "当前文章中有不确定的内容");
        }
        return flag;
    }

    /**
     * 审核失败更新文章状态
     *
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从文章中提取文本和图片
     *
     * @param wmNews
     * @return
     */
    private Map handleTextAndImages(WmNews wmNews) {
        StringBuffer text = new StringBuffer();
        ArrayList<String> images = new ArrayList<>();

        //获取文章内容
        if (wmNews.getContent() != null) {
            List<Map> contentList = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map content : contentList) {
                if ("text".equals(content.get("type"))) {
                    text.append(content.get("value"));
                }
                if ("image".equals(content.get("type"))) {
                    images.add(content.get("value").toString());
                }
            }
        }
        Map<String, Object> textAndImages = new HashMap<>();
        textAndImages.put("text", text.toString());
        textAndImages.put("images", images);
        return textAndImages;
    }
}
